package com.cea.papyrus.diagram.statemachine.dnd;

import java.util.Iterator;

import org.eclipse.gef.EditPart;
import org.eclipse.uml2.uml.Region;

import com.cea.papyrus.diagram.statemachine.editpart.RegionEditPart;
import com.cea.papyrus.diagraminterchange2.di2.DiagramElement;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;
import com.cea.papyrus.diagraminterchange2.di2.Uml1SemanticModelBridge;
import com.cea.papyrus.extensionpoints.dnd.utils.IFilter;

public class StateMachineDNDFilter implements IFilter {

	public boolean select(Object draggedObject, EditPart targetEditPart) {

		//additional tests for regions
		if (draggedObject instanceof Region) {
			if (targetEditPart instanceof RegionEditPart) {
				
				RegionEditPart regionEP = (RegionEditPart) targetEditPart;
				//check whether the container to be (statemachine or state) 
				// has not already got a node representing the region
				if (regionEP.getModel() == null) {
					return false;
				}
				
				GraphNode regionNode = (GraphNode) regionEP.getModel();				
				GraphNode semParent = (GraphNode) regionNode.getSemanticParent();
				
				if (semParent == null) {
					return false;
				}
				
				// Parse semantic child
				Iterator<DiagramElement> it = semParent.getSemanticChild().iterator();
				boolean found = false;
				while (!found && it.hasNext()) {
					
					GraphNode current = (GraphNode) it.next();
					if (current.getSemanticModel() != null) {
						Uml1SemanticModelBridge bridge = (Uml1SemanticModelBridge) current.getSemanticModel();
						
						if (bridge.getElement().equals(draggedObject)) {
							found = true;
						}
					}
				}
				if (found) {
					return false;
				} else {
					return true;
				}
			}				
		}
		return true;
	}
}
